package com.stardust.service;
/**
 * 注册或登录鉴权跳转服务实现类
 */

import com.stardust.mapper.UserMapper;
import com.stardust.pojo.ResultControl;
import com.stardust.pojo.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;

@Service
public class UserServiceImpl implements UserService{

    @Autowired
    private UserMapper userMapper;

    @Override
    public ResultControl Login(User user) {
        if (null != user.getUsername()){
            //如果用户名非空尝试在数据库中搜索此用户名
            User existUser = userMapper.getByUserName(user.getUsername());
            if (null == existUser){
                //如果数据库返回值为空返回用户名不存在
                return new ResultControl(ResultControl.ERROR,"此用户名不存在");
            }else {
                if (existUser.getPassword().equals(user.getPassword())){
                    //在用户名非空的情况下密码和数据库equals为true更新登录时间和ip
                    user.setId(existUser.getId());//将userid设置为当前登录用户的
                    user.setLoginDate(new Date());//更新用户登录时间
                    userMapper.update(user);//通过update函数更新用户信息
                    return new ResultControl();
                }else {
                    return new ResultControl(ResultControl.ERROR,"密码错误");
                }
            }
        }else {
            return new ResultControl(ResultControl.ERROR,"用户名不能为空");
        }
    }

    @Override
    public ResultControl Regist(User user) {
        if (null == user.getUsername()) {
            return new ResultControl(ResultControl.ERROR, "用户名不能为空");
        }else if (null == user.getPassword()){
            return new ResultControl(ResultControl.ERROR,"用户密码不能为空");
        }
        User existUser = userMapper.getByUserName(user.getUsername());
        if (null != existUser){
            return new ResultControl(ResultControl.ERROR,"用户名已存在");
        }
        userMapper.regist(user);
        ResultControl resultControl = new ResultControl();
        resultControl.data.put("value",user);
        return resultControl;
    }
}
